import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';

class LongListDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ListLongState();
}

class _ListLongState extends State<LongListDemo> {
  static const loadingTag = '##loading##';
  var _words = <String>[loadingTag];
  ScrollController _controller = ScrollController();
  bool showTopBtn = false;

  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      print(_controller.offset);
      if (_controller.offset < 1000 && showTopBtn) {
        setState(() {
          showTopBtn = false;
        });
      } else if (_controller.offset >= 1000 && !showTopBtn) {
        setState(() {
          showTopBtn = true;
        });
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('长列表示例'),
        centerTitle: true,
      ),
      body: ListView.separated(
        physics: BouncingScrollPhysics(),
        controller: _controller,
        itemCount: _words.length,
        itemBuilder: (context, index) {
          if (_words[index] == loadingTag) {
            if (_words.length - 1 < 100) {
              _retriveData();
              return Container(
                padding: EdgeInsets.all(16),
                alignment: Alignment.center,
                child: SizedBox(
                  width: 24,
                  height: 24,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                  ),
                ),
              );
            } else {
              return Container(
                alignment: Alignment.center,
                padding: EdgeInsets.all(16),
                child: Text('我也是有底线的', style: TextStyle(color: Colors.grey)),
              );
            }
          }
          return ListTile(
            leading: Icon(Icons.phone),
            title: Text(_words[index]),
          );
        },
        separatorBuilder: (context, index) => Divider(
          height: 0.5,
          indent: 15,
          endIndent: 15,
        ),
      ),
    );
  }

  //延迟任务
  void _retriveData() {
    Future.delayed(Duration(seconds: 3)).then((value) {
      setState(() {
        _words.insertAll(_words.length - 1,
            generateWordPairs().take(20).map((e) => e.asPascalCase).toList());
      });
    });
  }
}
